"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig")
const moment = require('moment');
const AuthException = require('../../exception/authException');
const SystemErrException = require("../../exception/systemError");
const Qiniu = require("../../utils/qiniu");
const { Op } = require("sequelize");

class MonitoringUnusualService extends Service {

  async monitoring() {
    let transaction;
    try {
      const { ctx } = this;
      transaction = await ctx.model.transaction();
      let partners = await ctx.model.Videos.MonitorPartners.findAll({
        where: {
          status: {
            [Op.in]: [1, 2, 3, 4]
          }
        },
        raw: true,
      });
      // 获取异常设备组单的ip
      let ips = [];
      let monitorPartners = [];
      partners.forEach(partner => {
        let { enterCameraIp, outCameraIp, id, monitorNums, monitorSeconds, status, maxPercent, monitorNumsUnusualDate, monitorSecondsDate } = partner;
        ips.push(enterCameraIp, outCameraIp);
        monitorPartners.push({
          enterCameraIp, outCameraIp, id, monitorNums, monitorSeconds, status, maxPercent, monitorNumsUnusualDate, monitorSecondsDate
        })
      });
      // 获取异常ip的最新一条信息
      let ipLogsPromises = ips.map(async unitip => {
        let newest = await ctx.model.Videos.Logs.findOne({
          where: {
            unitip
          },
          attributes: ['count', 'unitip', 'datetime'],
          raw: true,
          order: [['datetime', 'desc']]
        });
        return newest;
      })
      let newestIpLogs = await Promise.all(ipLogsPromises);

      // 同一组组合在一起
      let partnerUnusualLogs = [];
      monitorPartners.forEach(partners => {
        let { id, enterCameraIp, outCameraIp, monitorNums, monitorSeconds, maxPercent, status } = partners;
        // status: 1、设防中，2、滞留车辆数预警，3、滞留时间预警，4，警报中，5，排查中，6，停止工作
        let enterCameraIpewestData = newestIpLogs.filter(log => log.unitip == enterCameraIp)[0];
        let outCameraIpNewestData = newestIpLogs.filter(log => log.unitip == outCameraIp)[0];
        let inNums = enterCameraIpewestData.count;
        let outNums = outCameraIpNewestData.count;
        // 检测是否滞留车辆数异常
        if (inNums - outNums >= monitorNums * maxPercent) {
          partners.status = 2;
          if (!partners.monitorNumsUnusualDate) {
            partners.monitorNumsUnusualDate = new Date();
          }
        }
        // 检测时间
        let timeDiff = moment(outCameraIpNewestData.datetime).diff(moment(enterCameraIpewestData.datetime), "second");
        if (partners.status == 2 && timeDiff > monitorSeconds) {
          partners.status = 3;
          partners.monitorSecondsDate = new Date();
        }

        if (partners.monitorNumsUnusualDate && partners.monitorSecondsDate) {
          partners.status = 4;
        }

        partnerUnusualLogs.push({
          partnerId: id,
          monitorNumsUnusualDate: partners.monitorNumsUnusualDate,
          monitorSecondsDate: partners.monitorSecondsDate,
          status: partners.status,
          inNums,
          outNums
        })
      });
      // 更新
      if (partnerUnusualLogs.length != 0) {
        await ctx.model.Videos.UnusualLogs.bulkCreate(partnerUnusualLogs);
      }
      if (monitorPartners.length != 0) {
        await ctx.model.Videos.MonitorPartners.bulkCreate(monitorPartners, { updateOnDuplicate: ['status', 'monitorNumsUnusualDate', 'monitorSecondsDate'], ignoreDuplicates: true });
      }
      console.log('监控中...')
    } catch (error) {
      await transaction.rollback();
      throw new SystemErrException("检测设备组查询异常：" + error);
    }
  }

}

module.exports = MonitoringUnusualService;
